from ..models import Menu


def init_permission(request, user_obj):
    """
    初始化用户权限, 写入session
    :param request: 
    :param user_obj: 
    :return: 
    """
    permission_item_list = user_obj.roles.values('permissions__url',
                                                 'permissions__name',
                                                 'permissions__isOnly',
                                                 'permissions__image',
                                                 'permissions__menu_id',
                                                 'permissions__menu__type').distinct()
    # print(permission_item_list)
    # for i in permission_item_list:
    #     print(i)

    permission_url_list = []  # 用户权限url列表，--> 用于中间件验证用户权限
    permission_menu_list = []  # 用户权限url所属菜单列表 [{"title":xxx, "url":xxx, "menu_id": xxx},{},]
    for item in permission_item_list:
        permission_url_list.append(item['permissions__url'])
        # 从用户表跨到角色表再跨到权限表，权限表有外键menu与菜单表进行关联，
        # 如果有菜单id，则单独取出来，放到权限菜单列表中。
        if item['permissions__menu_id'] and item['permissions__menu__type'] == 0:
            temp = {"name": item['permissions__name'],
                    "url": item["permissions__url"],
                    "isOnly": item["permissions__isOnly"],
                    "image": item["permissions__image"],
                    "menu_id": item["permissions__menu_id"]}
            permission_menu_list.append(temp)

    menu_list = list(
        Menu.objects.values('id', 'title', 'parent_id', 'image').filter(type=0).order_by('orderId'))  # 取出type为0所有菜单
    # 注：session在存储时，会先对数据进行序列化，因此对于Queryset对象写入session， 加list()转为可序列化对象

    from django.conf import settings

    # 保存用户权限url列表
    # print('permission_url_list ------------------- ', permission_url_list)
    # print('permission_menu_list ------------------- ', permission_menu_list)  # admin用户有9种权限（）
    # print('menu_list----------- ------------------- ', menu_list) #

    request.session['id'] = user_obj.customerid

    request.session[settings.SESSION_PERMISSION_URL_KEY] = permission_url_list

    # 保存 权限菜单 和所有 菜单
    request.session[settings.SESSION_MENU_KEY] = {
        settings.ALL_MENU_KEY: menu_list,
        settings.PERMISSION_MENU_KEY: permission_menu_list,
    }

    # print('request.session[settings.SESSION_PERMISSION_URL_KEY] ------------------- ', request.session[
    # settings.SESSION_PERMISSION_URL_KEY])


